#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "sockets_unix.h"


#define ADDRESS "unix_sockets_address"

int serverCreateSocket(void)
{
  unlink(ADDRESS);
  clientConnectSocket();
}

int clientConnectSocket(void)
{
  register int i, s, ns, len;
  struct sockaddr_un saun, fsaun;

  if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
  {
    kLog(2,"No se pudo crear el socket","System",getpid(),0);
    printf("No se pudo crear el socket\n");
    return -1;
  }

  saun.sun_family = AF_UNIX;
  strcpy(saun.sun_path, ADDRESS);

  unlink(ADDRESS);
  len = sizeof(saun.sun_family) + strlen(saun.sun_path);

  if (bind(s, &saun, len) < 0)
  {
    kLog(2,"No se pudo bindear el socket","System",getpid(),0);
    printf("No se pudo bindear el socket\n");
    return -1;
  }

  return s;
}

int CloseSocket(int s)
{
  return close(s);
}

char *ServerListenSocket(int s)
{
  int fromlen;
  struct sockaddr_un fsaun;
  register int ns;

  if (listen(s, 5) < 0)
  {
    kLog(2,"No se pudo escuchar el socket","System",getpid(),0);
    printf("No se pudo escuchar el socket\n");
    return NULL;
  }

  if ((ns = accept(s, &fsaun, &fromlen)) < 0)
  {
    kLog(2,"No se pudo aceptar la conexion al socket","System",getpid(),0);
    printf("No se pudo aceptar la conexion al socket\n");
    return NULL;
  }

  /*TODO decision lectura escritura... loop infinito?*/
}

int WriteSocket(int s, char *input)
{
  return send(s,input,strlen(input),0);
}

char *ReadSocketByLine(int s)
{
  char c;
  FILE *fp;

  fp = fdopen(s, "r");

  while ((c = fgetc(fp)) != EOF)
  {
    putchar(c);

    if (c == '\n') break;
  }

  return c;
}

char *ReadSocket(int s)
{
  char c;
  FILE *fp;

  fp = fdopen(s, "r");

  while ((c = fgetc(fp)) != EOF)
  {
    putchar(c);
  }

  return c;
}
